package com.sky.controller;

/*
 *用户：sky-吴
 *日期：2020/4/22
 */

import com.jfinal.log.Log;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.upload.UploadFile;
import com.sky.model.User;
import io.jboot.web.controller.JbootController;
import io.jboot.web.controller.annotation.RequestMapping;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.*;

@RequestMapping("/")
public class IndexController extends JbootController {
    Log logger = Log.getLog(IndexController.class);
    public String msg = "";

    public void index() {

        String username = "kia";
        set("username", username);
        User user = new User(1, username, "", new Date());

        set("user", user);
        ArrayList<User> userList = new ArrayList<>();
        userList.add(new User(2, "aa", "123", new Date()));
        userList.add(new User(3, "bb", "123", new Date()));
        userList.add(new User(4, "cc", "123", new Date()));
        set("userList", userList);

        Map<Integer, User> userMap = new HashMap<>();
        userMap.put(1, new User(2, "aa", "123", new Date()));
        userMap.put(2, new User(3, "bb", "123", new Date()));
        userMap.put(3, new User(4, "cc", "123", new Date()));
        set("userMap", userMap);
        set("msg", msg);
        logger.info("我还在执行!!!!!!!");
        render("index.html");
        logger.info("我还在执行!!!!!!!");

    }

    //http://127.0.0.1:8080/dbtest
    public void dbTest() {
        logger.info("dbtest");
        List<Record> records = Db.find("select * from user");
        renderText(Arrays.toString(records.toArray()));
    }

    public void upload() {
        UploadFile uploadFile = null;
        try {

            uploadFile = getFile("uploadFile");
            if (uploadFile == null) {
                msg = "please upload a file!!";
                set("msg", msg);
                this.index();
                return;
            }
        } catch (Exception e) {
            this.index();
            logger.error(e.getMessage(), e);
            return;
        }

        logger.debug(uploadFile.getOriginalFileName());
        logger.debug(uploadFile.getFileName());
        logger.debug(uploadFile.getUploadPath());
        logger.debug(uploadFile.getContentType());
		/*
		first.png
		first.png
		E:-Java-codeLibraries\javaEE\jbootdemo\target\classes\template-upload
		image/png
		*/
        File file = uploadFile.getFile();
        logger.debug(String.valueOf(file.exists()));
        set("msg", "");
        this.index();
    }


    public void test() {
        //MessageUtil.sendAMsg();
        renderText("hello world");
    }

    public void servletUpload() throws IOException {
        HttpServletRequest request=getRequest();
        // TODO Auto-generated method stub

        //1.对上传的文件进行归类管理
        //获取Uploads在文件系统中的路径
		/*String basePath = request.getServletContext().getRealPath("/uploads");
		String tempPath = request.getServletContext().getRealPath("/temp");
		Calendar calendar = Calendar.getInstance(Locale.CHINA);

		String subPath = calendar.get(Calendar.YEAR) + "/" + calendar.get((Calendar.MONTH) + 1);
		System.out.println(basePath + "/" + subPath);
		File file = new File(basePath + "/" + subPath);
		if (!file.exists()) {
			file.mkdirs();//创建多级目录，根据日期变化创建不同的文件目录分类保存文件
		}
		File file2 = new File(tempPath);
		if (!file2.exists()) {
			file.mkdirs();//如果没有改目录则创建
		}*/


        //2.文件上传的处理
        //文件项工厂类
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(5 * 1024); //最大缓存
        factory.setRepository(new File("/temp"));//临时文件目录
        //设置上传参数
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setSizeMax(5 * 1024 * 1024);//文件最大上限

        try {
            List<FileItem> items = upload.parseRequest(request);
            for (FileItem fileItem : items) {
				//判断是否是文件, 是文件则处理
				if (!fileItem.isFormField()) {
                    //..防止未上传文件时发生异常, 对文件名长度进行判断
                    String fileName = fileItem.getName().toLowerCase();//把文件名统一转换成小写
                    int beginIndex = fileName.lastIndexOf(".");
                    //..判断拓展名是否合法, 合法则判断是什么鬼文件
                    System.out.println(beginIndex);
                    String fileType = fileName.substring(beginIndex);
                    System.out.println("fileType" + fileType);
                    //重命名上传后的文件
                    String randomFileName = UUID.randomUUID().toString().toLowerCase() + fileType;
                    System.out.println("上传后的文件名randomFileName是:" + randomFileName);

                    File uploadFile = new File("/" + randomFileName);
                    System.out.println("uploadFile" + uploadFile.getAbsolutePath());

					//执行上传
					fileItem.write(uploadFile);

					//fileItem.delete();//文件上传成功，删除临时文件

                    //本例把数据传递到success页面进行保存处理

                    //3.对上传后的路径进行保存或处理
					msg="上传文件ok";
					this.index();
					return;
                } else {
                    //不是一个文件, 只是一个文本,则进行相应处理
                    String filedName = fileItem.getFieldName();
                    System.out.println(filedName);
                    String value = fileItem.getString();
					msg="你没有上传文件";
					this.index();
					return;
				}
            }
        } catch (FileUploadException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }catch (Exception e) {
			e.printStackTrace();
		}
    }
}